package com.yummiii.dokueditor.view;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import org.apache.xmlrpc.XmlRpcException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;

import com.yummiii.dokueditor.controller.MainController;

public class MainPage {

	/**
	 * @param args
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 * @throws XmlRpcException 
	 */
	public static void main(String[] args) throws FileNotFoundException, IOException, XmlRpcException {

		//TODO: need to clean up
		final MainController mainController=new MainController();
		
//		RowLayout layout=new RowLayout(SWT.HORIZONTAL|SWT.FILL);
//		layout.fill=true;
		
		GridLayout layout=new GridLayout();
		layout.numColumns=2;
		
		Display display = new Display ();
		
		Shell shell = new Shell (display,SWT.SHELL_TRIM);
		
		
		shell.setText("DokuEditor");
		shell.setLayout(layout);
		
		ToolBar toolbar = mainController.getDummyToolbar(shell, display);
		GridData data = new GridData(GridData.FILL_BOTH);
		data.horizontalSpan = 2;
		data.verticalSpan = 1;
		toolbar.setLayoutData(data);

		
		
		Menu menu=mainController.getDummyMenu(shell);
		
		shell.setMenuBar(menu);
		
//		layout.pack=false;
		final Tree pageTree=mainController.getTree(shell);
		pageTree.pack();
//		pageTree.setSize(100,200);
		final StyledText textArea=mainController.getDummyText(shell, display);
		
		
		GridData gData=new GridData();
		gData.horizontalAlignment = SWT.FILL;
		gData.verticalAlignment=SWT.FILL;
		gData.widthHint=400;
		textArea.setLayoutData(gData);
		
		shell.pack();
		gData.widthHint=textArea.getBounds().width;
		gData.heightHint=textArea.getBounds().height;
		shell.pack();
		
		pageTree.addListener(SWT.MouseDown, new Listener () {
			public void handleEvent (Event event) {
				Point point = new Point (event.x, event.y);
				TreeItem item = pageTree.getItem (point);
				if (item != null) {
					System.out.println ("Mouse down: " + item);
					try {
						textArea.setText(mainController.getText(item));
						
					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (XmlRpcException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
		
//		shell.setSize (200, 200);
		shell.open ();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch ()) display.sleep ();
		}
		display.dispose ();
	}


}
